<template>
	<view class="pagebg">
		<!-- 翻转容器：控制透视，固定高度 -->

		<view class="flip-container" :class="{ flipped: isSearchVisible }">
			<!-- 翻转元素：承载正面和背面，是动画的核心载体 -->
			<view class="flipper">
				<!-- 正面：标签栏（初始显示） -->
				<view class="flip-panel front">
					<view class="search-bar">
						<view class="tabs-box">
							<uv-tabs :list="list" @click="handleTabClick" :current="currentTab"
								:activeStyle="{ fontWeight: 'bold' }"></uv-tabs>
						</view>
						<view class="search-img" @click="toggleSearch">
							<image :src="getImageUrl('icon-7.png')" mode="" alt="搜索图标"></image>
						</view>
					</view>
				</view>



				<!-- 背面：搜索栏（翻转后显示） -->
				<view class="flip-panel back">
					<view class="search-bar">
						<view class="tabs-search">
							<uv-search placeholder="请输入被访人名字" v-model="recordFrom.name" @search="hanldeSearch"
								:showAction="false"></uv-search>
							<uv-icon name="close" @click="toggleSearch" size="20px"></uv-icon>
						</view>
					</view>
				</view>
			</view>
		</view>


		<!-- 后端数据列表渲染 -->
		<scroll-view scroll-y="true" style="height:calc(95vh - 100px); padding: 20px 0px; box-sizing: border-box;"
			@scrolltolower="onScrollToLower">
			<view class="news-info" :class="item.auditStatus == 0 ? 'bg-pending' :
				        item.auditStatus == 1 ? 'bg-approved' : 
				        item.auditStatus == 2 ? 'bg-completed' : 
				        item.auditStatus == 3 ? 'bg-rejected' : 'bg-default'" v-for="(item, index) in recordList" :key="item.id"
				@click="handleToDetaols(item)">
				<view class="news-title">
					<view class="Visiting-status">
						拜访状态
					</view>

					<!-- 保安端 -->
					<view v-if="userType == '3'" class="Visiting-title" :class="item.visitStatus == 0 ? 'status-pending' :
					              item.visitStatus == 1 ? 'status-approved' : 
					              item.visitStatus == 2 ? 'status-completed' : 'status-default'">
						{{
						  item.visitStatus == 0 ? '待签到' : 
						  item.visitStatus == 1 ? '拜访中' : 
						  item.visitStatus == 2 ? '暂离开' :'' 
						}}
					</view>

					<!-- 访客、被访客 -->
					<view v-if="userType !== '3'" class="Visiting-title" :class="item.auditStatus == 0 ? 'status-pending' : 
					              item.auditStatus == 1 ? 'status-approved' : 
					              item.auditStatus == 2 ? 'status-completed' : 
					              item.auditStatus == 3 ? 'status-rejected' : 'status-default'">
						{{
						  item.auditStatus == 0 ? '待审核' : 
						  item.auditStatus == 1 ? '已通过' : 
						  item.auditStatus == 2 ? '已拒绝' :
						  item.auditStatus == 3 ? '已结束' :'' 
						}}
					</view>


				</view>
				<view class="news-item">
					<view class="item-box">
						<view class="item-title">来访人</view>
						<view class="result-text">{{ item.visitorName }}</view>
					</view>
					<view class="item-box">
						<view class="item-title">被访人</view>
						<view class="phone-box">
							<!-- <view class="phone">
								<image :src="getImageUrl('icon-5.png')" mode="" alt="电话图标"></image>
							</view> -->
							<view class="result-text">{{ item.intervieweeName }}</view>
						</view>
					</view>
					<view class="item-box">
						<view class="item-title">随访人数</view>
						<view class="result-text">{{ item.visitorPeopleNumber }}人</view>
					</view>
					<view class="item-box">
						<view class="item-title">来访时间</view>
						<view class="result-text">{{ item.visitorBeginDate }}</view>
					</view>
				</view>
			</view>

			<view v-if="noMore == true" class="empty-state">
				没有更多了
			</view>
		</scroll-view>

		<TabBar :currentIndex="1"></TabBar>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue'
	import {
		onShow,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app'
	import {
		$get,
		$post
	} from "@/utils/request.js"
	import TabBar from '../../components/TabBar/TabBar.vue';
	import {
		useStore
	} from 'vuex'
	const store = useStore() //引入vueX

	//1访客 2被访客 3保安
	const userType = ref('1')
	// 控制搜索框显示状态
	const isSearchVisible = ref(false)
	const list = ref([])
	watch(
		() => store.getters.getRoles,
		(newgetRoles) => {
			if (Array.isArray(newgetRoles) && newgetRoles.length > 0) {
				userType.value = newgetRoles[0];
				if (userType.value === '3') {
					list.value = [{
						name: '全部'
					}, {
						name: '待签到'
					}, {
						name: '拜访中'
					}, {
						name: '暂离开'
					}, ];

				} else {
					list.value = [{
						name: '全部'
					}, {
						name: '待审核'
					}, {
						name: '已通过'
					}, {
						name: '已拒绝'
					}, {
						name: '已结束'
					}];
				}
			}
		}, {
			immediate: true,
			deep: true
		}
	);

	onShareAppMessage(() => {
		return {
			title: '访客小程序分享', // 分享标题
			path: '/pages/index/index',
		}
	})

	onShareTimeline(() => {
		return {
			title: '访客小程序分享',
			path: '/pages/index/index'
		}
	})


	// 当前选中的标签索引
	const currentTab = ref(0)
	onShow(() => {
		const actIndex = uni.getStorageSync('actIndex')
		currentTab.value = Number(actIndex)
		recordFrom.value.pageNum = 1;
		noMore.value = false;

		if (userType.value == '3') {
			recordFrom.value.auditStatus = '1'
			getRecord()
		} else {
			if (currentTab.value == 0) {
				recordFrom.value.auditStatus = ''
				getRecord()
			} else {
				recordFrom.value.auditStatus = currentTab.value - 1
				getRecord()
			}
		}

		uni.setStorageSync('actIndex', 0);
	})

	// 微信环境图片路径处理 - 使用绝对路径 
	const getImageUrl = (fileName) => {
		return `/static/icon/${fileName}`;
	}





	//查询最新记录
	const recordList = ref([]) // 保持初始化为空数组
	const total = ref(0)
	const loading = ref(false)
	const noMore = ref(false)

	const recordFrom = ref({
		pageSize: 10,
		pageNum: 1,
		name: '',
		auditStatus: '',
		visitStatus: ''
	})

	const getRecord = () => {
		loading.value = true
		// 重置分页状态（切换条件时从第一页重新加载）
		if (recordFrom.value.pageNum == 1) {
			recordList.value = []
		}
		$get('/system/visitorInfo/list', recordFrom.value).then(res => {
			total.value = res.total
			if (recordFrom.value.pageNum == 1) {
				recordList.value = res.rows || []
			} else {
				recordList.value = [...recordList.value, ...(res.rows || [])]
			}

			// 判断是否还有更多数据
			noMore.value = recordList.value.length >= total.value
		}).finally(() => {
			loading.value = false
		})
	}

	// 分页加载
	const onScrollToLower = () => {
		if (loading.value || noMore.value) {
			return
		}
		// 加载下一页
		recordFrom.value.pageNum++
		getRecord()
	}

	//搜索事件

	const hanldeSearch = () => {
		// 直接从绑定的响应式数据中获取
		recordFrom.value.auditStatus = ''
		recordFrom.value.pageNum = 1;
		noMore.value = false;
		getRecord()
	}

	// 切换搜索框显示状态
	const toggleSearch = () => {
		isSearchVisible.value = !isSearchVisible.value
		if (!isSearchVisible.value) {
			recordFrom.value.name = ''
		}
	}

	// 处理标签点击事件
	const handleTabClick = (index) => {
		currentTab.value = index.index
		recordFrom.value.pageNum = 1;
		noMore.value = false; // 重置"没有更多"状态
		// visitStatus 是保安传值，访客和被访客不需要
		if (userType.value == '3') {
			recordFrom.value.auditStatus = '1'
			if (currentTab.value == 0) {
				recordFrom.value.visitStatus = ''
			} else {
				recordFrom.value.visitStatus = currentTab.value - 1
			}
			getRecord()


		} else {
			if (currentTab.value == 0) {
				recordFrom.value.auditStatus = ''
			} else {
				recordFrom.value.auditStatus = currentTab.value - 1
			}
			getRecord()
		}

	}


	// 预约详情
	const handleToDetaols = (item) => {
		if (userType.value == '3') { //保安端
			const itemStr = JSON.stringify(item)
			uni.navigateTo({
				url: `/pages/scanResults/scanResults?itemStr=${encodeURIComponent(itemStr)}`
			})
		} else { //访客和被访客
			const itemStr = JSON.stringify(item)
			uni.navigateTo({
				url: `/pages/record/recordDetails/recordDetails?itemStr=${encodeURIComponent(itemStr)}`
			})
		}
	}
</script>

<style lang="scss">
	.pagebg {
		width: 100vw;
		min-height: 100vh;
		background-color: #eff4fb;
		box-shadow: inset 0 4px 8px rgba(0, 0, 0, 0.15);
		padding: 10px;
		box-sizing: border-box;
	}

	// 翻转容器样式保持不变
	.flip-container {
		perspective: 1200px;
		width: 100%;
		height: 50px;
		position: relative;
	}

	.flipper {
		position: relative;
		width: 100%;
		height: 100%;
		transition: transform 0.5s ease;
		transform-style: preserve-3d;
	}

	.flip-panel {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		backface-visibility: hidden;
		overflow: hidden;
		background-color: #fff;
		border-radius: 6px;
		padding: 10px 6px;
		box-sizing: border-box;
	}

	.front {
		z-index: 2;
	}

	.back {
		transform: rotateX(180deg);
	}

	.flip-container.flipped .flipper {
		transform: rotateX(180deg);
	}

	.search-bar {
		width: 100%;
		height: 100%;
		padding: 10px 0px;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: space-around;
		gap: 10px;

	}

	.tabs-box {
		width: 88%;
		display: flex;
		align-items: center;
	}


	.search-img {
		width: 40rpx;
		height: 40rpx;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.tabs-search {
		width: 100%;
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.uv-icon {
		cursor: pointer;
		font-size: 20px;
		color: #666;
	}

	.uv-search {
		flex: 1;
		height: 36px;
	}

	// 状态卡片样式 - 使用CSS类定义背景图

	.news-info {
		width: 100%;
		height: 200px;
		margin-top: 16px;
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		border-radius: 15px;
		padding: 4px 20px;
		box-sizing: border-box;
		position: relative;

		.news-title {
			width: 100%;
			height: auto;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 2px 0px;

			.Visiting-status {
				color: var(--color-333);
				font-size: var(--font-16);
			}

			.Visiting-title {
				padding: 2px 8px;
				margin-top: 2px;
				box-sizing: border-box;
				border-radius: 50px;
				font-size: var(--font-16);
				font-weight: bold;
				border-style: solid;
				border-width: 1px;
			}
		}

		.news-item {
			width: 100%;
			height: 80%;
			margin-top: 4px;
			display: flex;
			flex-direction: column;
			justify-content: space-around;

			.item-box {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.item-title {
					color: var(--color-999);
					font-size: var(--font-16);
				}

				.result-text {
					color: var(--color-333);
					font-size: var(--font-16);
					font-weight: 800;
				}

				.phone-box {
					display: flex;

					.phone {
						width: 14px;
						height: 14px;
						margin-right: 6px;

						image {
							width: 100%;
							height: 100%;
						}
					}
				}
			}
		}
	}

	// 背景图通过CSS类定义，避免路径问题
	.bg-pending {
		background-image: url('/static/img/bg-5.png');
	}

	.bg-approved {
		background-image: url('/static/img/bg-2.png');
	}

	.bg-completed {
		background-image: url('/static/img/bg-4.png');
	}

	.bg-rejected {
		background-image: url('/static/img/bg-3.png');
	}

	.bg-default {
		background-image: url('/static/img/bg-5.png');
	}

	// 状态文字样式
	.status-pending {
		color: #ff8a00;
		border-color: #ff8a00;
	}

	.status-approved {
		color: #006aff;
		border-color: #006aff;
	}

	.status-completed {
		color: #11b800;
		border-color: #11b800;
	}

	.status-rejected {
		color: #707070;
		border-color: #707070;
	}

	.status-default {
		color: #666;
		border-color: #666;
	}

	.empty-state {
		text-align: center;
		padding: 50px 0;
		color: #999;
		font-size: 16px;
	}
</style>